package com.jz.netthings.netty.server;

import com.jz.netthings.netty.protocol.BasePacket;
import com.jz.netthings.netty.protocol.bean.ZxdcLoginPacket;
import com.jz.netthings.netty.protocol.bean.ZxdcMsgPacket;
import com.jz.netthings.netty.support.Attributes;
import com.jz.netthings.netty.support.ServerHandlerSupport;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("nettyZxdcServerHandler")
@ChannelHandler.Sharable
public class NettyZxdcServerHandler extends SimpleChannelInboundHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ServerHandlerSupport nettyServerHandlerSupport;

    private byte[] xmlBytes;

    public NettyZxdcServerHandler() {
//        System.out.println("NettyZxdcServerHandler 初始化....................................................................");
        ZxdcMsgPacket heartPacket = new ZxdcMsgPacket();
        heartPacket.setSeq(Long.toString(System.currentTimeMillis()));
        heartPacket.setCmd("online");
        heartPacket.setLevel(1);

        this.xmlBytes = NettyMsgHelper.packetToXml(heartPacket);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("handler 【"+ctx.channel().remoteAddress()+"】移除了............................................");
        ctx.close();
        super.handlerRemoved(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        System.out.println("【"+this+"】");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
//                logger.info("服务器给单采机【" + ctx.channel().remoteAddress() + "】发送心跳信息...");
                NettyMsgHelper.sendOnlineMsg(ctx);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        logger.info("【"+this+"】连接的客户端【nettyZxdcServerHandler】地址:" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {


        super.channelRead(ctx,obj);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {
//        System.out.println("NettyZxdcServerHandler channelRead0..."+obj);
//        System.out.println("【"+this+"】这个 ctx 的 channel ：" + ctx.channel().remoteAddress());
        if (obj instanceof ZxdcLoginPacket) {

            NettyMsgHelper.handlerZxdcLogin((ZxdcLoginPacket)obj,nettyServerHandlerSupport,ctx);
            NettyMsgHelper.sendTimeStampMsgToMc(ctx);

        } else if (obj instanceof byte[]) {
            byte[] msgByte = (byte[]) obj;
            ZxdcMsgPacket packet = NettyMsgHelper.xmlToPacket(msgByte);
            if (packet.getCmd() == null || "".equals(packet.getCmd())){
                packet = NettyMsgHelper.bytesToPacket(msgByte);
            }

            if(!"online".equals(packet.getCmd())){
                logger.info("单采机【" + ctx.channel().remoteAddress() + "】消息：【" + packet.getCmd()+" ： " + packet.getValues() +"】");
            }

            packet.setCtx(ctx);
            BasePacket handlePacket = nettyServerHandlerSupport.handlePacket(packet);

            if (handlePacket != null) {
                if (handlePacket instanceof ZxdcMsgPacket) {
                    NettyMsgHelper.sendPacket(ctx,(ZxdcMsgPacket) handlePacket);
                }
            }

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //捕捉异常信息
        logger.error(cause.getMessage() + "【" + ctx.channel().remoteAddress() + "】");
        nettyServerHandlerSupport.freeMachineData(ctx);
        //出现异常时关闭channel
        ctx.close();
        super.exceptionCaught(ctx,cause);
    }
}
